<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>layui</title>
    <meta name="renderer" content="webkit" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all" />
    <link rel="stylesheet" href="../../css/public.css" media="all" />
    <style>
      body {
        background-color: #ffffff;
      }
    </style>
  </head>
  <body>
    <div class="layui-form layuimini-form">
      <div class="layui-form-item">
        <label class="layui-form-label required">用户账号</label>
        <div class="layui-input-block">
          <input
            type="text"
            name="userName"
            lay-verify="required"
            lay-reqtext="用户账号不能为空"
            placeholder="请输入用户账号"
            value=""
            class="layui-input"
            disabled
          />
          <input type="hidden" name="userId" />
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">用户昵称</label>
        <div class="layui-input-block">
          <input type="text" name="nickName" placeholder="用户昵称" value="" class="layui-input" />
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label required">性别</label>
        <div class="layui-input-block">
          <input type="radio" name="sex" value="0" title="男" checked="" />
          <input type="radio" name="sex" value="1" title="女" />
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label required">手机</label>
        <div class="layui-input-block">
          <input
            type="number"
            name="phone"
            lay-verify="required"
            lay-reqtext="手机不能为空"
            placeholder="请输入手机"
            value=""
            class="layui-input"
          />
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">邮箱</label>
        <div class="layui-input-block">
          <input type="email" name="email" placeholder="请输入邮箱" value="" class="layui-input" />
        </div>
      </div>
      <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">备注信息</label>
        <div class="layui-input-block">
          <textarea name="remark" class="layui-textarea" placeholder="请输入备注信息"></textarea>
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">配置部门/角色</label>
        <div class="layui-input-block">
          <button class="layui-btn layui-btn-normal" id="openTree_btn">添加部门</button>
          <table
            class="layui-hide"
            id="currentTableId"
            lay-verify="deptData"
            lay-filter="currentTableId"
          ></table>
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-input-block">
          <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认保存</button>
        </div>
      </div>
    </div>
    <script id="dept-status" type="text/html">
      <input type="checkbox" name="enable" value="{{d.deptId}}" lay-skin="switch" lay-text="启用|禁用"
      lay-filter="dept-enable" {{ d.status == '0' ? 'checked' : '' }}>
    </script>
    <script type="text/html" id="dept-type">
      {{#if (d.type == 0) { }}
      <span>部门</span>
      {{# }else if(d.type == 1){ }}
      <span>分公司</span>
      {{# }else if(d.type == 2){ }}
      <span>地区</span>
      {{# } }}
    </script>
    <!-- 操作列 -->
    <script type="text/html" id="dept-state">
      <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">配置角色</a>
      <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">移除</a>
    </script>
    <script th:src="@{/lib/layui-v2.6.3/layui.js}" charset="utf-8"></script>
    <script th:src="@{/js/lay-config.js?v=1.0.4}" charset="utf-8"></script>
    <script>
      const tableData = new Map();

      function init11(formObj) {}
      layui.use(["form", "table", "dtree", "tableSelect"], function () {
        var form = layui.form,
          layer = layui.layer,
          table = layui.table,
          dtree = layui.dtree,
          tableSelect = layui.tableSelect,
          $ = layui.$;

        window.init = function (formObj) {
          $("[name='userId']").val(formObj.userId);
          $("[name='userName']").val(formObj.userName);
          $("[name='nickName']").val(formObj.nickName);
          $("[name='sex']").val(formObj.sex);
          $("[name='phone']").val(formObj.phone);
          $("[name='email']").val(formObj.email);
          $("[name='remark']").val(formObj.remark);
          $.ajax({
            url: "/sys-user/queryDeptRole/" + formObj.userId,
            type: "get",
            async: false,
            success: function (result) {
              if (result.success) {
                let data = result.data;
                for (let elem of data.values()) {
                  let deptObj = {};
                  deptObj.deptId = elem.deptId + "";
                  deptObj.deptName = elem.deptName;
                  deptObj.status = elem.status;
                  deptObj.roleNames = elem.roleNames.join();
                  deptObj.roleIds = elem.roleIds.join();
                  tableData.set(deptObj.deptId, deptObj);
                }
                renderTable();
              }
            },
          });
        };

        form.verify({
          deptData: function (value, item) {
            let deptData = table.getData("currentTableId");

            let validDepts = deptData.filter((x) => x.status == 0);
            if (validDepts.length == 0) {
              return "用户启用的部门不能为空";
            }
            for (let elem of validDepts.values()) {
              if (!elem.roleIds) {
                return elem.deptName + "的角色不能为空";
              }
            }
          },
        });

        //监听提交
        form.on("submit(saveBtn)", function (data) {
          let reqData = { ...data.field };
          reqData.depts = [];
          for (let elem of tableData.values()) {
            let deptUser = {};
            deptUser.deptId = elem.deptId;
            deptUser.status = elem.status;
            deptUser.roleIds = [];
            if (elem.roleIds) {
              deptUser.roleIds = elem.roleIds.split(",");
            }
            reqData.depts.push(deptUser);
          }
          layer.confirm("确认提交？", function (index) {
            $.ajax({
              url: "/sys-user/update",
              type: "post",
              async: false,
              data: JSON.stringify(reqData),
              contentType: "application/json",
              success: function (result) {
                if (result.success) {
                  layer.msg(result.msg, { icon: 1, time: 1000 }, function () {
                    parent.reload();
                    parent.layer.close(parent.layer.getFrameIndex(window.name));
                  });
                } else {
                  layer.msg(result.msg, { icon: 2, time: 3000 });
                }
              },
            });
          });
          return false;
        });

        // 渲染表格
        function renderTable() {
          table.render({
            elem: "#currentTableId",
            page: false,
            data: [...tableData.values()],
            cols: [
              [
                { field: "deptId", width: 80, title: "部门id" },
                { field: "deptName", minWidth: 130, title: "部门名称" },
                {
                  field: "status",
                  width: 200,
                  align: "center",
                  title: "部门状态",
                  templet: "#dept-status",
                },
                {
                  field: "type",
                  width: 200,
                  align: "center",
                  title: "部门类型",
                  templet: "#dept-type",
                },
                {
                  field: "roleNames",
                  minWidth: 200,
                  align: "center",
                  title: "角色",
                },
                {
                  templet: "#dept-state",
                  width: 200,
                  align: "center",
                  title: "操作",
                },
              ],
            ],
            done: function () {},
          });
        }
        window.addDataAndRefresh = function (deptId, roleNames, roleIds) {
          let currData = tableData.get(deptId);
          currData.roleNames = roleNames;
          currData.roleIds = roleIds;
          console.log(tableData);
          renderTable();
        };
        renderTable();

        form.on("switch(dept-enable)", function (obj) {
          var id = this.value;
          var name = this.name;
          let deptObj = tableData.get(id);
          deptObj.status = 1;
          if (obj.elem.checked) {
            deptObj.status = 0;
          }
          //layer.tips(id + " " + name + ": " + obj.elem.checked, obj.othis);
        });

        // 触发单元格工具事件
        table.on("tool(currentTableId)", function (obj) {
          var data = obj.data; // 获得当前行数据
          console.log(obj);
          if (obj.event === "edit") {
            var index = layer.open({
              title: "添加用户",
              type: 2,
              shade: 0.2,
              maxmin: true,
              shadeClose: false,
              area: ["80%", "80%"],
              content: "/page/user/addRole.html",
              yes: function (index, layero) {},
              success: function (layero, index, that) {
                var iframe = window["layui-layer-iframe" + index];
                iframe.test(data.roleIds, data.roleNames);
                var body = layer.getChildFrame("body", index);
                body.find("#deptId").val(data.deptId);
              },
            });
            $(window).on("resize", function () {
              layer.full(index);
            });
          } else if (obj.event === "del") {
            tableData.delete(data.deptId);
            renderTable();
          }
        });

        $("#openTree_btn").click(function () {
          layer.open({
            type: 1, //type:0 也行
            title: "选择部门",
            area: ["400px", "80%"],
            content: '<ul id="openTree1" class="dtree" data-id="0"></ul>',
            btn: ["确认选择"],
            success: function (layero, index) {
              var DTree = dtree.render({
                //  obj: $(layero).find("#openTree1"),    如果直接用elem加载不出来，则可以使用这个方式加载jquery的DOM
                elem: "#openTree1",
                initLevel: "2", //默认展开层级为1
                line: true, // 有线树
                ficon: ["1", "-1"], // 设定一级图标样式。0表示方形加减图标，8表示小圆点图标
                icon: ["0", "2"], // 设定二级图标样式。0表示文件夹图标，5表示叶子图标
                record: true, // 开启数据记录模式
                method: "post",
                url: "/sys-dept/query",
                dataStyle: "layuiStyle",
                dataFormat: "list",
                response: {
                  message: "msg",
                  statusCode: 0,
                  treeId: "deptId", //节点ID（必填）
                  parentId: "parentId", //父节点ID（必填）
                  title: "deptName", //节点名称（必填）},
                  type: "type1",
                },
              });
              // 绑定节点的双击
              dtree.on("nodedblclick('openTree1')", function (obj) {
                var recordData = obj.param.recordData; // 取出
                var deptObj = {};
                deptObj.deptId = obj.param.nodeId;
                deptObj.deptName = obj.param.context;
                deptObj.type = recordData.type;
                deptObj.status = 0;
                if (!tableData.has(deptObj.deptId)) {
                  tableData.set(deptObj.deptId, deptObj);
                }
                renderTable();
                layer.close(index);
              });
            },
            yes: function (index, layero) {
              var param = dtree.getNowParam("openTree1"); // 获取当前选中节点
              var recordData = param.recordData; // 取出
              var deptObj = {};
              deptObj.deptId = param.nodeId;
              deptObj.deptName = param.context;
              deptObj.type = recordData.type;
              if (!tableData.has(deptObj.deptId)) {
                tableData.set(deptObj.deptId, deptObj);
              }
              renderTable();
              layer.close(index);
            },
          });
        });
      });
    </script>
  </body>
</html>
